const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const common = require('../../core/common');
const stringUtils = require('../../core/util/StringUtils');
const assign = require('lodash/assign');

exports.add = async(ctx) => {
    let house_name = ctx.request.body.house_name || '';
    let house_create_time =  moment().format('YYYY-MM-DD HH:mm:ss');
    let house_update_time =  moment().format('YYYY-MM-DD HH:mm:ss');
    let house_type_id = ctx.request.body.house_type_id || 0;
    let buliding_id = ctx.request.body.buliding_id || 0;
    let floor = ctx.request.body.floor || '';
    let house_id = ctx.request.body.house_id || 0;
    //新建 非独立展示间的 样板房时 需传入 已有的houseid 进行 update
    let unit = ctx.request.body.unit || '';
    let household_num = ctx.request.body.household_num || '';
    let status = ctx.request.body.status || '';
    let is_model_house = ctx.request.body.is_model_house || '';
    //0:普通房 1:样板房
    let model_house_location = ctx.request.body.model_house_location || -1;

    //model_house_location 备注 ： 0:独立展示间 1:拼接地址building_name+unit+floor+household_num

    let newhouse = {
        house_name,
        house_create_time,
        house_update_time,
        house_type_id,
        buliding_id,
        floor,
        unit,
        household_num,
        status,
        is_model_house,
        model_house_location,
    };
    try{
        if(is_model_house && !model_house_location || !is_model_house) {
            if (house_name === '' || house_type_id <= 0 || buliding_id <= 0 || is_model_house === '') {
                ctx.body = {
                    result: 201,
                    message: "请检查参数"
                };
                return;
            }
            ret = await mysql.query(`INSERT INTO house SET ?`, newhouse);
            if (!ret || ret.insertId === -1){
                ctx.body = {
                    result: 202,
                    message: "新增样板房失败"
                };
            } else {
                ctx.body = {
                    result: 200,
                    id: ret.insertId,
                    message: "新增样板房成功"
                };
            }
        }
        else if (is_model_house && model_house_location) {
            if (house_id <= 0 ) {
                ctx.body = {
                    result: 201,
                    message: "请检查参数"
                };
                return;
            }
            let selectRows = await mysql.query(`SELECT * FROM house WHERE house_id = ?`, house_id);
            if (selectRows.length > 0) {
                console.log('selectRows:', selectRows);
                let update_data = assign({}, selectRows[0],ctx.body)
                ret = await mysql.query(`UPDATE house SET ? WHERE house_id= ? `, [update_data,house_id]);
                console.log(ret);
                if (!ret || ret.insertId === -1) {
                    ctx.body = {
                        result: 202,
                        message: "更新失败"
                    };
                } else {
                    ctx.body = {
                        result: 200,
                        message: "更新成功"
                    };
                }
            } else {
                ctx.body = {
                    result: 203,
                    message: "对象不存在或者已删除"
                };
            }
        }



    }catch (e) {
        ctx.body = {
            result: 203,
            message: "新增房开商失败"+e.toString()
        };
    }
}

exports.delete = async(ctx) => {
    let house_id = ctx.params.house_id || 0;
    if (house_id <= 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return
    }
    try{
        ret = await mysql.query(`delete from house WHERE house_id = ?`, house_id);
        console.log(ret);
        if (!ret || ret.insertId === -1){
            ctx.body = {
                result: 202,
                message: "删除失败"
            };
        } else {
            ctx.body = {
                result: 200,
                message: "删除成功"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 203,
            message: "删除失败"+e.toString()
        };
    }
}

exports.update = async(ctx) => {
    let house_id = ctx.request.body.house_id || 0;
    let house_name = ctx.request.body.house_name || '';

    if (house_id <= 0 || house_name === '') {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
    }else{
        try {
            let selectRows = await mysql.query(`SELECT * FROM house WHERE house_id = ?`, house_id);
            if (selectRows.length > 0) {
                console.log('selectRows:', selectRows);
                let update_data = assign({}, selectRows[0],ctx.body);
                ret = await mysql.query(`UPDATE house SET ? WHERE house_id= ? `, [update_data,house_id]);
                console.log(ret);
                if (!ret || ret.insertId === -1) {
                    ctx.body = {
                        result: 202,
                        message: "更新失败"
                    };
                } else {
                    ctx.body = {
                        result: 200,
                        message: "更新成功"
                    };
                }
            } else {
                ctx.body = {
                    result: 203,
                    message: "对象不存在或者已删除"
                };
            }
        }catch (e) {
            ctx.body = {
                result: 204,
                message: "更新失败"+e.toString()
            };
        }
    }
}


exports.getList = async(ctx) => {
    let create_user_id = ctx.user.id || '';
    let project_id = ctx.query.project_id;
    // let is_model_house = ctx.query.is_model_house;
    let building_id = ctx.query.building_id;
    let counts = ctx.query.counts || 10;
    let indexfrom = ctx.query.indexfrom || 0;

    if (create_user_id === ''){
        ctx.body = {
            result: 201,
            message: "无效的用户id"
        };
    } else {
        try {
            if (project_id) {
                let results = await mysql.query(`SELECT * FROM v_project_detail where project_id =${project_id} ORDER BY house_id LIMIT ${indexfrom}, ${counts} `);
                ctx.body = {
                    result: 200,
                    list:results,
                    message: "查询该项目对应房屋成功成功"
                };
            } else if (building_id) {
                let results = await mysql.query(`SELECT * FROM house where building_id =${building_id} ORDER BY house_id LIMIT ${indexfrom}, ${counts} `);
                ctx.body = {
                    result: 200,
                    list:results,
                    message: "查询该楼幢对应房屋成功"
                };
            }else {
                //查询所有的 house list 进行展示
                let results = await mysql.query(`SELECT * FROM house  ORDER BY house_id LIMIT ${indexfrom}, ${counts} `);
                ctx.body = {
                    result: 200,
                    list:results,
                    message: "查询成功"
                };
            }
        }catch (e) {
            ctx.body = {
                result: 205,
                message: "数据库错误 " + e.toString()
            };
        }
    }
}

exports.getDetail = async(ctx)=>{
    let houseId = ctx.params.house_id;
    if (!houseId ){
        ctx.body = {
            result: 201,
            message: "请携带houseid"
        };
    }
    try {
    let house = await mysql.query(`SELECT * FROM v_house_detail  where house_id = ${houseId}`);
    let houseResult = house && house[0];
    let house_type_id = houseResult.house_type_id;
    houseResult.scenario_list = await mysql.query(`SELECT * FROM scenario  where house_type_id = ${house_type_id}`);
    houseResult.room_list = await mysql.query(`SELECT * FROM room  where house_type_id = ${house_type_id}`);
    for(let i = 0; i < houseResult.room_list.length; i++) {
        houseResult.room_list[i].room_product_list = await mysql.query(`SELECT * FROM v_temp_device_detail  where room_id = ${houseResult.room_list[i].room_id}`);
    }
    ctx.body = {
        result: 200,
        results: houseResult,
        message: "返回成功"
    };}
    catch (e) {
        ctx.body = {
            result: 205,
            message: "数据库错误 " + e.toString()
        };
    }
}